package org.apache.ibatis.lgtest.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author lg
 * @description
 * @create 2019-09-18
 **/
public class BlockClient {

  public static void main(String[] args) {
    Logger logger = Logger.getLogger("tlg");

    Socket socket = null;
    try {
      socket = new Socket("localhost", 12345);
    } catch (IOException e) {
      logger.log(Level.INFO, "连接服务器失败" + e.toString());
    }
    BufferedWriter writer = null;

    try {
      writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
      BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

      //用一个单独的线程监听服务端消息
      new Thread(()->{
        while(true){
          String line = null;
          try {
            line = reader.readLine();
          } catch (IOException e) {
            logger.log(Level.INFO, "读取服务端消息失败" + e.toString());
          }
          System.out.println("收到服务端消息："+line);
        }
      }).start();

    } catch (IOException e) {
      logger.log(Level.INFO, "获取输入/输出流失败" + e.toString());
    }

    System.out.println("客户端连接服务端成功");

    String resp =null;
    BufferedReader screenReader = new BufferedReader(new InputStreamReader(System.in));

    while(true){
      try {
        resp = screenReader.readLine();
      } catch (IOException e) {
        e.printStackTrace();
      }

      try {
        writer.write(resp);
        writer.write("\n");
        writer.flush();
      } catch (IOException e) {
        logger.log(Level.INFO, "向服务器发送消息失败" + e.toString());
      }


    }

  }
}
